package cn.tworice.monitor.interceptor;

import cn.tworice.common.vo.RequestResult;
import cn.tworice.ip.util.IpAddrUtils;
import cn.tworice.monitor.service.RequestFlowService;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MonitorInterceptor implements HandlerInterceptor {
    @Resource
    private RequestFlowService requestFlowService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String origin  = request.getHeader(HttpHeaders.ORIGIN);
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Token, adminID");
            response.setHeader("Access-Control-Max-Age", "3600");
        }

        if(!requestFlowService.enter(request)){
            returnJson(response, "您的请求被识别为恶意请求");
        }
        if(requestFlowService.sqlInject(request)){
            returnJson(response, "您的请求被识别为恶意请求");
        }
        return true;
    }

    /**
     * 请求被拦截后返回给客户端数据
     * @author 二饭
     * @Email 1786705138@qq.com
     */
    private void returnJson(HttpServletResponse response,String message){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        String jsonString = JSON.toJSONString(RequestResult.error(401,message));
        try {
            writer = response.getWriter();
            writer.print(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
